Free Hosting

Constants


C++ has two kinds of constants: literal, and symbolic.
Literal constants
Literal constants are literal numbers inserted into the code. They are constants because you can’t change their values.
1
int x = 5; // 5 is a literal constant
Literal constants can have suffixes that determine their types. Integer constants can have a u or U suffix that means they are unsigned. Integer constants can also have a l or L suffix, which means they are long integers. However, these suffixes are typically optional, as the compiler can usually tell from context what kind of constant you need.
1
2
unsigned int nValue = 5u; // unsigned constant
long nValue2 = 5L; // long constant
By default, floating point literal constant have a type of double. To convert them into a float value, the f or F suffix can be used:
1
float fValue = 5.0f; // float constant
Floating point literal constants can also use an l or L suffix to make them long doubles.
Generally, it is a good idea to try to avoid using literal constants that aren’t 0 or 1. For more detail, you can review the section onmagic numbers, and why they are a bad idea.
Symbolic constants
As you learned in a previous lesson, you can use the #define preprocessor directive in order to declare a symbolic constant:
1
2
#define YEN_PER_DOLLAR  122
int nYen = nDollars * YEN_PER_DOLLAR;
There are two major problems with symbolic constants declared using #define. First, because they are resolved by the preprocessor, which replaces the symbolic name with the defined value, #defined symbolic constants do not show up in the debugger. Thus, if you only saw the statement int nYen = nDollars * YEN_PER_DOLLAR;, you would have to go looking for the #define declaration in order to find out what value of YEN_PER_DOLLAR was used.
Second, #defined values always have global scope (which we’ll talk about in the section on local and global variables). This means a value #defined in one piece of code may have a naming conflict with a value #defined with the same name in another piece of code.
A better way to do symbolic constants is through use of the const keyword. Const variables must be assigned a value when declared, and then that value can not be changed. Here is the way the above snippet of code should be written:
1
2
const int nYenPerDollar = 122;
int nYen = nDollars * nYenPerDollar;
Declaring a variable as const prevents us from inadvertently changing it’s value:
1
2
const int nYenPerDollar = 122;
nYenPerDollar = 123; // compiler error!
Although a constant variable might seem like an oxymoron, they can be very useful in helping to document your code and avoid magic numbers. Some programmers prefer to use all upper-case names for const variables (to match the style of #defined values). However, we will use normal variable naming conventions, which is more common. Const variables act exactly like normal variables in every case except that they can not be assigned to.

0 comments:

Blogger Template by Clairvo